package com.gxd.commons.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:gxd
 * @Description:
 * @Date: 9:55 2018/9/7
 * @Modified By:
 */
public class DeviceUtils {

    public static String android="Android";
    public static String iphone="iPhone";
    public static String ipad="iPad";
    public static String noDevice="未知设备";


    /**
     * 判断是否是移动设备
     * @param request
     * @return
     */
    public static boolean isMobileDevice(HttpServletRequest request) {
        String ua = request.getParameter("ua");
        if (StringUtils.isNotBlank(ua)) {
            return "ios".equals(ua) || "android".equals(ua);
        } else {
            String userAgent = request.getHeader("User-Agent");
            return userAgent.matches(".*"+android+".*") || userAgent.matches(".*"+iphone+".*") || userAgent.matches(".*"+ipad+".*");
        }
    }

    /**
     * 获取用户Browser信息
     * @param ua
     * @return
     */
    public static String getBrowser(String ua){
        if(null == ua) {
            return "";
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        Browser browser = userAgent.getBrowser();
        return browser.toString();
    }
    /**
     * 获取用户手机型号
     * @param userAgent
     * @return
     */
    public static String getPhoneModel(String userAgent){
        if(null == userAgent || "" == userAgent) {
            return noDevice;
        }
        String OS = getMobileOS(userAgent);
        if (OS.equals(android)) {
            String rex="[()]+";
            String[] str=userAgent.split(rex);
            str = str[1].split("[;]");
            String[] res=str[str.length-1].split("Build/");
            return res[0];
        }else if (OS.equals(iphone)) {
            String[] str=userAgent.split("[()]+");
            String res="iphone"+str[1].split("OS")[1].split("like")[0];
            return res;
        }else if (OS.equals(ipad)) {
            return ipad;
        }else {
            return getOS(userAgent);
        }
    }

    /**
     * 获取用户os信息
     * @param ua
     * @return
     */
    public static String getOS(String ua){
        if(null == ua){
            return noDevice;
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        OperatingSystem os = userAgent.getOperatingSystem();
        return os.toString();
    }

    /**
     * 获取移动用户操作系统
     * @param userAgent
     * @return
     */
    public static String getMobileOS(String userAgent){
        if (userAgent.contains(android)) {
            return android;
        }else if (userAgent.contains(iphone)){
            return iphone;
        }else if (userAgent.contains(ipad)){
            return ipad;
        }else {
            return "others";
        }
    }
}
